﻿using eSSP_example.Entity;
using eSSP_example.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eSSP_example.Database
{
    public class TokenStore
    {
        public const int USE_TOKEN_AUTH     =   1;
        public const int INDEX_SIZE         =   30;

        private const int EXPIRE_MS         =   12 * 60 * (60 * 1000);

        //  mydb
        private DbHelperService mydb = DbHelperService.getInstance();

        //  this class is a singleton and should not be instantiated directly!
        private static TokenStore instance = new TokenStore();

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static TokenStore getInstance()
        {
            return  instance;
        }

        //  private constructor so people know to use the
        //  getInstance() function instead
        private TokenStore()
        {

        }

        /*
        *   Generates a token for the username, stores that token along with an
        *   expiration time, and then returns the token so clients can store it.
        */
        public TokenResponse putToken(String username)
        {
            Guid    uuid = Guid.NewGuid();
            string  token = uuid.ToString();

            //  clear
            mydb.cleanApiToken();

            TokenResponse rsp = new TokenResponse();
            rsp.access_token = token;
            rsp.token_type = "bearer";
            rsp.expires_in = EXPIRE_MS;
            rsp.userName = username;

            long currentMilliseconds = DateTime.Now.Ticks / 10000;
            mydb.insertToken(token, username, currentMilliseconds + EXPIRE_MS);

            return  rsp;
        }

        /**
         * Returns the username mapped to the username, or null
         * if the token isn't found or has expired.
         */
        public String getUsername(String token)
        {
            TokenResponse rsp = mydb.getTokenData(token);

            if  (rsp != null)
            {
                //  long exp = System.currentTimeMillis();
                long exp = DateTime.Now.Ticks / 10000;

                if  (rsp.expires_in > exp)
                {
                    return  rsp.userName;
                }
                else
                {
                    mydb.deleteToken(token);
                }
            }

            return  null;
        }
    }
}
